package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmdp.config.RabbitMQConfig;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.SeckillMessage;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.User;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Autowired
    private ISeckillVoucherService seckillVoucherService;
    @Autowired
    private RedisIdWorker redisIdWorker;
    @Autowired
    private StringRedisTemplate simpleRedisLock;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    private  IVoucherOrderService proxy;
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
       SECKILL_SCRIPT = new DefaultRedisScript<>();
       SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
       SECKILL_SCRIPT.setResultType(Long.class);
    }
    //阻塞队列
//    private BlockingQueue<VoucherOrder> orderQueue=new ArrayBlockingQueue<>(1024*1024);
    //线程池
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();
    @PostConstruct // 服务启动时执行
    private void init() {
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }
    private class VoucherOrderHandler implements Runnable {
        String queueName="stream.orders";
        @Override
        public void run() {
           while (true){
               try {
                   //获取队列中的订单信息 XREADGROUP GROUPID $group $consumerId  COUNT 1 BLOCK 2000 stream stream.order >
                   List<MapRecord<String, Object, Object>> read = simpleRedisLock.opsForStream().read(
                           Consumer.from("g1", "c1"),
                           StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                           StreamOffset.create(queueName, ReadOffset.lastConsumed())
                   );
                   //判段消息是否获取成功
                   if(read== null||read.isEmpty()) {
                       //获取失败，说明没有消息！进入下一轮循环
                       continue;
                   }
                   //解析消息
                   MapRecord<String, Object, Object> record = read.get(0);
                   //获取订单信息
                   Map<Object, Object> value = record.getValue();
                   //将Map转化为voucherOrder对象
                   VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                   //获取成功以后创建订单
                   createVoucherOrder(voucherOrder);

                   //ACK确认消息SACK streams.order g1 id
                   simpleRedisLock.opsForStream().acknowledge(queueName,"g1",record.getId());

               }catch (Exception e){
                   //一旦抛出异常，就进行重试
                   log.error("处理订单异常", e);
                       handlePendingList();

               }
           }

        }

        private void handlePendingList() {
            while (true){
                try {
                    //获取pending-liist的订单信息 XREADGROUP GROUPID $group $consumerId  COUNT 1 stream stream.order 0
                    List<MapRecord<String, Object, Object>> read = simpleRedisLock.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create(queueName, ReadOffset.from("0"))
                    );
                    //判段消息是否获取成功
                    if(read== null||read.isEmpty()) {
                        //获取失败，说明没有异常信息了！退出循环
                        break;
                    }
                    //解析消息
                    MapRecord<String, Object, Object> record = read.get(0);
                    //获取订单信息
                    Map<Object, Object> value = record.getValue();
                    //将Map转化为voucherOrder对象
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    //获取成功以后创建订单
                    createVoucherOrder(voucherOrder);

                    //ACK确认消息SACK streams.order g1 id
                    simpleRedisLock.opsForStream().acknowledge(queueName,"g1",record.getId());

                }catch (Exception e){
                    log.error("处理pending-list异常", e);
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException ex) {
                       ex.printStackTrace();
                    }
                }
                }
            }

        private void createVoucherOrder(VoucherOrder voucherOrder) {
            //获取用户
            Long userid = voucherOrder.getUserId();
            //创建锁对象
            RLock lock = redissonClient.getLock("lock:order:" + userid);
            //获取锁
            boolean b = false;
            try {
                b = lock.tryLock(1, 10, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //判段是否获取锁成功
            if(!b){
                log.error("用户{}重复下单， voucherId:{}", voucherOrder.getUserId(), voucherOrder.getVoucherId());
            }
            try {
                //获取锁对象
                proxy.getResult(voucherOrder);
            }finally {
                //释放锁
                lock.unlock();
            }
        }
    }
    //基于Redis来判断优惠卷库存和一人一单
//    @Override
//    public Result seckillVoucher(Long voucherId) throws InterruptedException {
//        //TODO:获取用户
//        UserDTO user = UserHolder.getUser();
//        //运行Lua脚本
//        Long execute = simpleRedisLock.execute(
//                SECKILL_SCRIPT,
//                Collections.emptyList(),
//                voucherId.toString(),
//                UserHolder.getUser().getId().toString()
//
//        );
//        int returnCode = execute.intValue();
//        if (returnCode != 0){
//            return Result.fail(returnCode == 1 ? "库存不足" : "请勿重复下单");
//        }
//
//        //返回订单id
//        Long orderId = redisIdWorker.nextId("order");
//        //TODO:判段完成以后证明是由购买资格的！
//        //TODO:阻塞队列完成订单
//        //使用RabbitMQ完成订单
//        // 创建秒杀消息
//        SeckillMessage seckillMessage = new SeckillMessage(user, voucherId);
//
//        // 发送消息到RabbitMQ
//        rabbitTemplate.convertAndSend(
//                RabbitMQConfig.SECKILL_EXCHANGE,
//                "seckill.order",
//                seckillMessage
//        );
//
//        // 返回订单ID，告知用户下单已受理
//        return Result.ok(orderId);
//    }
    //基于Redis的判段和Redis的Stream消息队列完成
    @Override
    public Result seckillVoucher(Long voucherId) throws InterruptedException {
        //TODO:获取用户
        UserDTO user = UserHolder.getUser();
        //返回订单id
        Long orderId = redisIdWorker.nextId("order");
        //运行Lua脚本
        Long execute = simpleRedisLock.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                UserHolder.getUser().getId().toString(),
                orderId.toString()

        );
        int returnCode = execute.intValue();
        if (returnCode != 0){
            return Result.fail(returnCode == 1 ? "库存不足" : "请勿重复下单");
        }
        //TODO:初始化代理对象想
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        //返回订单id
        return Result.ok(orderId);
    }
//    @Override
//    public Result seckillVoucher(Long voucherId) throws InterruptedException {
//        //TODO:1.获取到优惠卷信息
//        SeckillVoucher voucher =seckillVoucherService.getById(voucherId);
//        //判段优惠卷是否存在
//        if (voucher == null) {
//            return Result.fail("没有该优惠卷");
//        }
//        //TODO:2.判断秒杀是否开始和结束
//        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {//判段使用时间大于当前时间
//            return Result.fail("秒杀尚未开始");
//        }
//        if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
//            return Result.fail("秒杀已经结束");
//        }
//        //TODO:3.判断库存是否充足
//        if (voucher.getStock() < 1) {
//            return Result.fail("库存不足");
//        }
//        //获取用户
//        Long userId = UserHolder.getUser().getId();
//        //TODO:添加锁，防止一个用户夺下到
//        synchronized (userId.toString().intern()) {
//            //创建锁
//            //TODO:使用初代分布式锁,由于我们是优惠点下点业务！key的前缀为order,但又由于我们想要以用户id不同来加锁，因此锁的key为order:userId
//            SimpleRedisLock simpleRedisLock1 = new SimpleRedisLock("order:" + userId, simpleRedisLock);
//            RLock lock1 = redissonClient.getLock("order:" + userId);
//            //TODO:使用redisson锁
//            //获取锁
////            boolean lock = simpleRedisLock1.tryLock(1200);
//            boolean lock = lock1.tryLock(1,1200, TimeUnit.MILLISECONDS);//失败不等待无参！
//            if (!lock) {
//                //TODO:获取锁失败，返回错误
//                return Result.fail("请勿重复下单");
//            }
//            try {
//                //获取代理对象，防止事务失效
//                IVoucherOrderService iVoucherOrderService = (IVoucherOrderService) AopContext.currentProxy();
//                return iVoucherOrderService.getResult(voucherId);
//            }finally {
//                //释放锁
//                simpleRedisLock1.unlock();
//            }
//
//
//        }
//    }

    @Transactional
        public void getResult(VoucherOrder voucherOrder) {

        //TODO:实现一人一单
        LambdaQueryWrapper<VoucherOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VoucherOrder::getUserId, voucherOrder.getUserId());
        wrapper.eq(VoucherOrder::getVoucherId, voucherOrder.getVoucherId()); // 正确

        int count = (int) count(wrapper);
        if (count > 0) {
            log.error("用户{}已经购买过该优惠券， voucherId:{}", voucherOrder.getUserId(), voucherOrder.getVoucherId());
        }

        //TODO:4.扣除库存
        //TODO:使用乐观锁（CAS方法）来解决锁的问题！eq("stock", voucher.getStock())//判断库存是否充足，但是使用等于判断，因为有可能在查询之后，被其他线程修改了！会导致在库存充足的情况下，出现很多错误！
        //我们希望的是当库存大于零的时候可以修改！使用gt("stock",0)来代替！
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherOrder.getVoucherId()) // 正确
                .gt( "stock", 0)
                .update();//使用手动的修改sql修改！将库存值减一！条件为：id等于传入的id
        if (!success) {
            log.error("库存不足， voucherId:{}", voucherOrder.getVoucherId());
            return; // 库存不足，直接返回，不创建订单
        }
        // 只有库存扣减成功，才保存订单
        save(voucherOrder);

    }
}
